package org.example.chat;

import java.io.*;
import java.net.*;
import java.util.function.Consumer;

public class ChatClient {
    private Socket clientSocket;      // 客户端套接字
    private PrintWriter out;          // 输出流，用于发送数据
    private BufferedReader in;        // 输入流，用于接收数据
    private Consumer<String> messageHandler;  // 消息处理器

    public void startConnection(String ip, int port, Consumer<String> messageHandler) throws IOException {
        this.messageHandler = messageHandler;
        // 步骤1：创建套接字
        // 步骤2：连接到服务器（通过构造函数完成）
        clientSocket = new Socket(ip, port);
        
        // 步骤3：创建输入输出流，用于与服务器通信
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        
        // 启动新线程监听服务器消息
        new Thread(this::listenForMessages).start();
    }

    // 监听服务器发送的消息
    private void listenForMessages() {
        String msg;
        try {
            while ((msg = in.readLine()) != null) {
                messageHandler.accept(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 发送消息到服务器
    public void sendMessage(String msg) {
        out.println(msg);
    }

    // 步骤4：关闭连接
    public void stopConnection() throws IOException {
        in.close();
        out.close();
        clientSocket.close();
    }
} 